<template>
  <div class="app-container question-new">
    <el-card class="card">
      <!-- 头部的标签 -->
      <div class="title">{{ $route.query.id? '试题修改':'试题录入' }}</div>
      <hr>
      <!-- form表单 -->
      <el-form ref="form" :model="qsForm" :rules="qsRules" class="demo-form-inline" label-width="120px">
        <!-- 学科 选择器 -->
        <el-form-item label="学科：" prop="subjectID">
          <el-select v-model="qsForm.subjectID" style="width: 400px" placeholder="请选择学科" @change="getTagsOptions">
            <el-option v-for="item in subjectOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 目录 选择器 -->
        <el-form-item label="目录：" prop="catalogID">
          <el-select v-model="qsForm.catalogID" style="width: 400px" placeholder="请选择目录">
            <el-option v-for="item in catalogOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!--  企业 选择器 -->
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select v-model="qsForm.enterpriseID" style="width: 400px" placeholder="请选择企业">
            <el-option v-for="item in CompanyOptions" :key="item.id" :label="item.company" :value="item.id" />
          </el-select>
        </el-form-item>
        <!--  城市 选择器 -->
        <el-form-item label="城市：" prop="city">
          <el-select v-model="qsForm.province" style="width: 200px" placeholder="请选择市" @focus="getprovinceOptions" @change="getAreaOptions">
            <el-option v-for="item in provinceOptions" :key="item" :label="item" :value="item" />
          </el-select>
          <el-select v-model="qsForm.city" style="width: 200px" placeholder="请选择具体城市">
            <el-option v-for="item in citysOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <!-- 方向 选择器 -->
        <el-form-item label="学科：" prop="direction">
          <el-select v-model="qsForm.direction" style="width: 400px" placeholder="请选择方向">
            <el-option v-for="item in directionOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <!-- 题型 选择器 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="qsForm.questionType">
            <el-radio v-for="item in questionType" :key="item.value" :label="item.value+''">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 选择器 -->
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="qsForm.difficulty">
            <el-radio v-for="item in difficulty" :key="item.value" :label="item.value+''">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 富文本编辑器 -->
        <el-form-item label="题干：" prop="question">
          <!-- content富文本编辑器的默认内容 options富文本编辑器配置选项 事件(change,blur......) -->
          <quill-editor v-model="qsForm.question" :options="editorOptions" @blur="checkQustion" />
          <!-- <quillEditor v-model="qsForm.question" :options="editorOptions"></quillEditor> -->
          <!-- <quill-editor @blur="checkQustion" v-model="qsForm.question" :options="editorOptions"></quill-editor> -->
        </el-form-item>
        <!-- 选项 上面的题型选择器联动 -->
        <el-form-item v-if="qsForm.questionType !== '3'" label="选项：" prop="options">
          <div v-for="item in qsForm.options" :key="item.code" class="option_item">
            <el-radio v-if="qsForm.questionType === &quot;1&quot;" v-model="item.isRight" :label="true" style="margin-right:0" @change="changeRadio(item)">{{ item.code }}:</el-radio>
            <el-checkbox v-if="qsForm.questionType === &quot;2&quot;" v-model="item.isRight" style="margin-right:0">{{ item.code }}: </el-checkbox>
            <el-input v-model="item.title" style="width:240px" />
            <el-upload
              style="margin-left:4px"
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :headers="{'Authorization':'Bearer '+ token}"
              :on-success="(res,file)=>{uploadSuccess(item,res,file)}"
              :show-file-list="false"
            >
              <img v-if="item.img" :src="item.img" alt="">
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close" @click.stop="delOption(item.code)" />
            </el-upload>
          </div>
          <!-- 添加按钮 -->
          <el-button type="danger" :disabled="qsForm.questionType!=='2'" size="small" @click="addOption">+增加选项与答案</el-button>
        </el-form-item>
        <!-- 解析视频 input输入框 -->
        <el-form-item label="解析视频：">
          <el-input v-model="qsForm.videoURL" style="width:400px" />
        </el-form-item>
        <!-- 答案解析 和选项联动 -->
        <el-form-item label="答案解析：" prop="question">
          <quill-editor v-model="qsForm.answer" :options="editorOptions" />
        </el-form-item>
        <!-- 题目备注 文本域 -->
        <el-form-item label="题目备注：">
          <el-input
            v-model="qsForm.remarks"
            style="width:400px"
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
          />
        </el-form-item>
        <!-- 试题标签 复选框-->
        <el-form-item label="试题标签：" prop="tags">
          <el-select v-model="qsForm.tags" style="width: 400px" multiple filterable allow-create default-first-option placeholder="请选择试题标签">
            <el-option v-for="item in TagsOptions" :key="item.value" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button v-if="!$route.query.id" type="primary" @click="submit">确认提交</el-button>
          <el-button v-else type="primary" @click="update">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { simple as getSubjectOptions } from '../../api/hmmm/subjects'
import { simple as getcatalogOptions } from '../../api/hmmm/directorys'
import { simple as getTagOptions } from '../../api/hmmm/tags'
import { list as getCompanyOptions } from '../../api/hmmm/companys'
import { add, detail, update } from '../../api/hmmm/questions'
import { provinces as getCityOptions, citys as getAreaOptions } from '../../api/hmmm/citys'
import { direction as directioned, difficulty, questionType } from '../../api/hmmm/constants'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import hljs from 'highlight.js'
import { getToken } from '@/utils/auth'
export default {
  name: 'QuestionsNew',
  components: { quillEditor },
  data() {
    return {
      token: getToken(),
      // 富文本配置
      // 1. 使用 highlight.js 插件处理高亮
      // 2. 安装  npm i highlight.js
      // 3. 导入  代码语法风格的样式   转换文本插件
      // 4. 配置 富文本  实时输入的时候高亮效果
      // 富文本编辑器默认内容
      // content: '<h2>请输入题干</h2>',
      // 富文本编辑器配置
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote'], // 引用
            ['code-block', 'image', 'link'] // 代码块、图片、引用
          ],
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      // 试题对象
      qsForm: {
        subjectID: '', // 双向绑定的下拉学科
        catalogID: '', // 选择的目录
        enterpriseID: '', // 企业
        city: '', // 城市
        province: '', // 市
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 富文本内容
        videoURL: '', // 视频解析地址
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [], // 试题标签数组
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      },
      // 校验规则
      qsRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请选择试题标签', trigger: 'change' }
        ]
      },
      subjectOptions: [], // 学科下拉列表的数组
      catalogOptions: [], // 目录下拉列表的数组
      CompanyOptions: [], // 企业的下拉列表
      provinceOptions: [], // 市列表
      citysOptions: [], // 城市列表
      directionOptions: directioned, // 方向数据
      TagsOptions: [], // 学科的试题标签的下拉列表
      questionType, // 题型
      difficulty // 难度
    }
  },
  // 监听器地址栏发生改变的时候，改变数据
  watch: {
    '$route.query': function() {
      if (this.$route.query.id) {
        this.getQusetion()
      } else {
        this.qsForm = {
          subjectID: '', // 双向绑定的下拉学科
          catalogID: '', // 选择的目录
          enterpriseID: '', // 企业
          city: '', // 城市
          province: '', // 市
          direction: '', // 方向
          questionType: '1', // 题型
          difficulty: '1', // 难度
          question: '', // 富文本内容
          videoURL: '', // 视频解析地址
          answer: '', // 答案解析
          remarks: '', // 题目备注
          tags: [], // 试题标签数组
          // 选项
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    }
  },
  created() {
    this.getSubjectOptions()
    this.getCompanyOptions()
    if (this.$route.query.id) {
      this.getQusetion()
    }
  },
  methods: {
    // 获取数据
    async getQusetion() {
      const { data } = await detail({ id: this.$route.query.id })
      // const { data } = await detail({ id: 20 })
      // console.log(res)
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.qsForm = data
      const res = await getcatalogOptions({ subjectID: this.qsForm.subjectID })
      this.catalogOptions = res.data
      const result = await getTagOptions({ subjectID: this.qsForm.subjectID })
      this.TagsOptions = result.data
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    // 新增提交事件
    submit() {
      this.$refs.form.validate(async ds => {
        if (ds) {
          const data = { ...this.qsForm }
          data.tags = data.tags.join(',')
          await add(data)
          this.$message.success('新增成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 新增修改提交事件
    update() {
      this.$refs.form.validate(async ds => {
        if (ds) {
          const data = { ...this.qsForm }
          data.tags = data.tags.join(',')
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 单选框的矫正更新
    changeRadio(item) {
      this.qsForm.options.forEach(item => {
        item.isRight = false
      })
      item.isRight = true
      // console.log(item.isRight)
      // console.log(this.qsForm.options)
    },
    // 校验题干
    checkQustion() {
      // 调用el-form组件的 validateField 校验  question  字段
      this.$refs.form.validateField('question')
    },
    // 删除选项
    delOption(code) {
      const list = this.qsForm.options.filter(item => item.code !== code)
      this.list = list.map((item, index) => { item.code = String.fromCharCode(65 + index) })
      this.qsForm.options = list
    },
    // 新增选项
    addOption() {
      this.qsForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.qsForm.options.length),
        title: '',
        img: ''
      })
    },
    // 获取学科的下拉列表
    async getSubjectOptions() {
      const { data } = await getSubjectOptions()
      // console.log(data)
      this.subjectOptions = data
    },
    // 获取企业列表
    async getCompanyOptions() {
      const res = await getCompanyOptions({ pagesize: 10000 })
      // console.log(res)
      this.CompanyOptions = res.data.items
    },
    // 获取市列表
    async getprovinceOptions() {
      const res = await getCityOptions()
      // console.log(res)
      this.provinceOptions = res
    },
    // 获取城市列表
    getAreaOptions() {
      this.qsForm.city = ''
      // console.log(this.qsForm.province)
      const res = getAreaOptions(this.qsForm.province)
      // console.log(res)
      this.citysOptions = res
    },
    // 获取标签下拉列表框
    async getTagsOptions() {
      // 获取目录下拉列表
      this.qsForm.catalogID = ''
      const { data } = await getcatalogOptions({ subjectID: this.qsForm.subjectID })
      // console.log(data)
      this.catalogOptions = data
      this.qsForm.tags = null
      const res = await getTagOptions({ subjectID: this.qsForm.subjectID })
      // console.log(res)
      this.TagsOptions = res.data
    },
    // 获取上传成功图片的url地址
    uploadSuccess(item, res, file) {
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      item.img = URL.createObjectURL(file.raw)
    }
  }
}
</script>

<style scoped lang='scss'>
.question-new ::v-deep .ql-editor{
  height: 200px;
}
.option_item{
  padding-bottom: 5px;
}
.question-new ::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.question-new ::v-deep .avatar-uploader i{
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%,-50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar-uploader{
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}
.question-new {
  .card {
    margin: 20px,10px,0,10px;
    .title {
      padding-bottom: 15px;
      width: 100%;
      border: 1px,solid,#ccc;
    }
  }
}

</style>
